package com.gwz.sys.controller;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gwz.sys.service.LogInfoService;
import com.gwz.sys.utils.ActiverUser;
import com.gwz.sys.utils.ResultObj;
import com.gwz.sys.utils.WebUtils;
import com.gwz.sys.vo.LogInfoVo;

@RestController
@RequestMapping("login")
public class LoginController {
	
	@Autowired
	private LogInfoService logInfoService;

	@RequestMapping("login")
	public ResultObj login(String userName, String pwd) {
		// 1,封装用户名和密码
		UsernamePasswordToken token = new UsernamePasswordToken(userName, pwd);
		// 2,得到Subject
		Subject subject = SecurityUtils.getSubject();
		// 3,完成认证
		String msg = "登陆成功";
		try {
			subject.login(token);
			System.out.println("认证成功");
			ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
			WebUtils.getCurrentSession().setAttribute("user", activerUser.getUser());
			LogInfoVo logInfoVo = new LogInfoVo();
			logInfoVo.setLoginname(activerUser.getUser().getName()+"-"+activerUser.getUser().getLoginname());
			logInfoVo.setLoginip(WebUtils.getCurrentRequest().getRemoteAddr().toString());
			logInfoVo.setLogintime(new Date());
			logInfoService.addLogInfo(logInfoVo);
			return new ResultObj(HttpStatus.OK.value(), msg);
		} catch (IncorrectCredentialsException e) {
			System.out.println("密码不正确");
			msg = "密码不正确";
		} catch (UnknownAccountException e) {
			System.out.println("用户名不存在");
			msg = "用户名不存在";
		}
		return new ResultObj(-1, msg);
	}
}
